<template>
  <div class="payment-container">
    <div class="payment-header">
      <h1>订单支付</h1>
    </div>
    
    <el-card v-if="loading" class="loading-card">
      <el-skeleton :rows="3" animated />
    </el-card>
    
    <el-card v-else-if="!orderInfo" class="error-card">
      <div class="error-message">
        <el-empty description="订单信息不存在" />
        <el-button type="primary" @click="goBack">返回订单列表</el-button>
      </div>
    </el-card>
    
    <template v-else>
      <el-card class="order-info-card">
        <div class="card-header">
          <h2>订单信息</h2>
        </div>
        <div class="order-detail">
          <div class="detail-item">
            <span class="label">订单号：</span>
            <span class="value">{{ orderInfo.orderNumber }}</span>
          </div>
          <div class="detail-item">
            <span class="label">下单时间：</span>
            <span class="value">{{ formatDate(orderInfo.orderDate) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">订单金额：</span>
            <span class="value amount">¥{{ (orderInfo.totalAmount || 0).toFixed(2) }}</span>
          </div>
        </div>
      </el-card>
      
      <el-card class="payment-card">
        <div class="card-header">
          <h2>选择支付方式</h2>
        </div>
        
        <div class="payment-methods">
          <div 
            class="payment-method"
            :class="{ 'selected': paymentMethod === 'alipay' }"
            @click="paymentMethod = 'alipay'"
          >
            <div class="method-icon alipay-icon"></div>
            <div class="method-name">支付宝</div>
          </div>
          
          <div 
            class="payment-method"
            :class="{ 'selected': paymentMethod === 'wechat' }"
            @click="paymentMethod = 'wechat'"
          >
            <div class="method-icon wechat-icon"></div>
            <div class="method-name">微信支付</div>
          </div>
        </div>
        
        <div class="payment-actions">
          <div class="total-amount">
            <span>需支付：</span>
            <span class="amount">¥{{ (orderInfo.totalAmount || 0).toFixed(2) }}</span>
          </div>
          
          <el-button 
            type="primary" 
            :loading="paying"
            @click="handlePayment"
          >
            {{ paying ? '处理中...' : '立即支付' }}
          </el-button>
        </div>
      </el-card>
      
      <!-- 支付二维码对话框 -->
      <el-dialog
        v-model="showQrDialog"
        title="请扫码支付"
        width="400px"
        center
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :show-close="false"
      >
        <div class="qrcode-container">
          <div v-if="qrLoading" class="qr-loading">
            <el-skeleton :rows="5" animated />
          </div>
          <div v-else>
            <div v-html="paymentForm" class="payment-form"></div>
            <div v-if="!paymentForm" class="qrcode-placeholder">
              <p>正在生成支付二维码，请稍候...</p>
            </div>
          </div>
          
          <div class="qrcode-footer">
            <p class="qrcode-tip">请使用支付宝扫描二维码完成支付</p>
            <p class="qrcode-price">¥{{ (orderInfo.totalAmount || 0).toFixed(2) }}</p>
            
            <div class="qrcode-actions">
              <el-button @click="cancelPayment" type="default">取消支付</el-button>
              <el-button @click="goToOrderList" type="primary">已完成支付</el-button>
            </div>
          </div>
        </div>
      </el-dialog>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getOrderById } from '../../../api/order';
import { createAlipayOrder, checkPaymentStatus } from '../../../api/payment';

const route = useRoute();
const router = useRouter();
const orderId = ref<number>(parseInt(route.params.orderId as string));

// 页面状态
const loading = ref(true);
const paying = ref(false);
const orderInfo = ref<any>(null);

// 支付相关
const paymentMethod = ref('alipay');
const showQrDialog = ref(false);
const paymentForm = ref('');
const qrLoading = ref(false);
const paymentPolling = ref<any>(null); // 轮询支付状态的定时器

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '未知';
  try {
    const date = new Date(dateString);
    if (isNaN(date.getTime())) return dateString;
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  } catch {
    return dateString;
  }
};

// 获取订单信息
const fetchOrderInfo = async () => {
  if (!orderId.value) {
    ElMessage.error('订单ID无效');
    loading.value = false;
    return;
  }
  
  try {
    const response = await getOrderById(orderId.value);
    if (response && response.code === 200 && response.data) {
      orderInfo.value = response.data;
    } else {
      ElMessage.error(response?.message || '获取订单信息失败');
    }
  } catch (error) {
    console.error('获取订单信息异常:', error);
    ElMessage.error('获取订单信息时发生错误');
  } finally {
    loading.value = false;
  }
};

// 返回订单列表
const goBack = () => {
  router.push('/user/orders');
};

// 支付订单
const handlePayment = async () => {
  if (!orderInfo.value) {
    ElMessage.warning('订单信息不存在');
    return;
  }
  
  if (paying.value) return;
  
  paying.value = true;
  qrLoading.value = true;
  showQrDialog.value = true;
  
  try {
    if (paymentMethod.value === 'alipay') {
      const response = await createAlipayOrder({
        orderId: orderInfo.value.id,
        orderNumber: orderInfo.value.orderNumber,
        totalAmount: orderInfo.value.totalAmount,
        subject: `美妆商城订单-${orderInfo.value.orderNumber}`,
        body: `订单包含${orderInfo.value.orderItems?.length || 0}件商品`,
        returnUrl: `${window.location.origin}/user/orders`
      });
      
      if (response && response.code === 200) {
        paymentForm.value = response.data;
        // 自动提交表单
        setTimeout(() => {
          const formElement = document.querySelector('.payment-form form');
          if (formElement) {
            (formElement as HTMLFormElement).submit();
          }
        }, 100);
        
        // 开始轮询支付状态
        startPollingPaymentStatus();
      } else {
        ElMessage.error(response?.message || '创建支付订单失败');
        showQrDialog.value = false;
      }
    } else if (paymentMethod.value === 'wechat') {
      ElMessage.info('微信支付功能暂未开通，请使用支付宝支付');
      showQrDialog.value = false;
    }
  } catch (error) {
    console.error('支付异常:', error);
    ElMessage.error('创建支付订单时发生错误');
    showQrDialog.value = false;
  } finally {
    paying.value = false;
    qrLoading.value = false;
  }
};

// 开始轮询支付状态
const startPollingPaymentStatus = () => {
  if (paymentPolling.value) clearInterval(paymentPolling.value);
  
  paymentPolling.value = setInterval(async () => {
    try {
      if (!orderInfo.value) return;
      
      const response = await checkPaymentStatus(orderInfo.value.orderNumber);
      if (response && response.code === 200) {
        if (response.data.paid) {
          // 支付成功
          clearInterval(paymentPolling.value);
          ElMessage.success('支付成功');
          setTimeout(() => {
            goToOrderList();
          }, 1500);
        }
      }
    } catch (error) {
      console.error('检查支付状态异常:', error);
    }
  }, 3000); // 每3秒检查一次
};

// 取消支付
const cancelPayment = () => {
  if (paymentPolling.value) clearInterval(paymentPolling.value);
  showQrDialog.value = false;
  ElMessage.info('已取消支付');
};

// 跳转到订单列表
const goToOrderList = () => {
  if (paymentPolling.value) clearInterval(paymentPolling.value);
  router.push('/user/orders');
};

// 组件挂载时获取订单信息
onMounted(() => {
  fetchOrderInfo();
});

// 组件卸载时清除轮询
onUnmounted(() => {
  if (paymentPolling.value) clearInterval(paymentPolling.value);
});
</script>

<style scoped>
.payment-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.payment-header {
  margin-bottom: 20px;
}

.payment-header h1 {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.loading-card, .error-card {
  padding: 20px;
  margin-bottom: 20px;
}

.error-message {
  text-align: center;
  padding: 30px 0;
}

.order-info-card, .payment-card {
  margin-bottom: 20px;
}

.card-header {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 15px;
  margin-bottom: 15px;
}

.card-header h2 {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.order-detail {
  padding: 10px 0;
}

.detail-item {
  display: flex;
  margin-bottom: 10px;
}

.detail-item .label {
  width: 100px;
  color: #606266;
}

.detail-item .value {
  flex: 1;
  color: #303133;
}

.detail-item .amount {
  color: #f56c6c;
  font-weight: 600;
}

.payment-methods {
  display: flex;
  gap: 20px;
  margin: 20px 0;
}

.payment-method {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.payment-method:hover {
  border-color: #409eff;
}

.payment-method.selected {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.method-icon {
  width: 32px;
  height: 32px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  margin-right: 10px;
}

.alipay-icon {
  background-image: url('https://img.alicdn.com/imgextra/i4/O1CN01XtT6Zn1XDvbiY4V8W_!!6000000002900-55-tps-46-44.svg');
}

.wechat-icon {
  background-image: url('https://cdn.iconscout.com/icon/free/png-256/free-wechat-pay-1852850-1569905.png');
}

.method-name {
  font-size: 16px;
  color: #303133;
}

.payment-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.total-amount {
  font-size: 16px;
}

.total-amount .amount {
  font-size: 20px;
  color: #f56c6c;
  font-weight: bold;
}

.qrcode-container {
  text-align: center;
  padding: 20px 0;
}

.qr-loading {
  padding: 20px;
}

.qrcode-placeholder {
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
}

.qrcode-footer {
  margin-top: 20px;
}

.qrcode-tip {
  color: #606266;
  margin-bottom: 10px;
}

.qrcode-price {
  font-size: 24px;
  color: #f56c6c;
  font-weight: bold;
  margin-bottom: 20px;
}

.qrcode-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 20px;
}

/* 支付表单样式 */
.payment-form {
  max-width: 100%;
  overflow: hidden;
}
</style> 